/**    
 * @{#} BuweiActivity.java Create on 2014-6-9 下午8:50:36    
 *          
 * @author <a href="mailto:evan0502@qq.com">Evan</a>   
 * @version 1.0    
 */
package com.smiier.skin;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import cn.o.app.json.JsonUtil;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.ui.OImageView;
import cn.o.app.ui.OTab;
import cn.skinapp.R;

import com.evan.common.handler.RequestHandler;
import com.evan.common.handler.callback.HandlerCallback;
import com.evan.common.pullrefresh.PullToRefreshBase;
import com.evan.common.pullrefresh.PullToRefreshBase.OnRefreshListener;
import com.evan.common.pullrefresh.PullToRefreshListView;
import com.pifuke.adapter.QuestionDetailAdapter;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.extra.QuestionAnswerExtra;
import com.smiier.skin.intercept.RequestTaskIntercept;
import com.smiier.skin.net.FollowSetTask;
import com.smiier.skin.net.FollowSetTask.FollowSetRequest;
import com.smiier.skin.net.FollowSetTask.FollowSetResponse;
import com.smiier.skin.net.QuestionGetListTask;
import com.smiier.skin.net.QuestionGetListTask.QuestionGetListRequest;
import com.smiier.skin.net.QuestionGetListTask.QuestionGetListResponse;
import com.smiier.skin.net.QuestionGetTask;
import com.smiier.skin.net.QuestionGetTask.QuestionGetRequest;
import com.smiier.skin.net.QuestionGetTask.QuestionGetResponse;
import com.smiier.skin.net.entity.QuestionAnswer;
import com.smiier.skin.net.entity.User;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.ui.PersonDetailView;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;

public class QuestionDetailActivity extends BasicActivity implements
		OnRefreshListener<ListView>, OnClickListener {

	public PullToRefreshListView list_question_detail;
	QuestionDetailAdapter adapter;

	HashMap<String, Object> params = new HashMap<String, Object>();
	Long start_qid;
	ArrayList<QuestionAnswer> array = new ArrayList<QuestionAnswer>();
	JSONObject question, user;

	TextView text_job, text_guominshi, text_bingshi; // ,text_patient_name
	OImageView img_patient_icon;
	LinearLayout ll_yaowuguomin, ll_bingshi, footView, ll_buliang_guominshi;

	ImageView img_loading;
	Button btn_load_more_question_detail;

	// 表示是否以查看用户详情的方式来显示本页
	private boolean isViewProfile;
	private PersonDetailView mPersonDetail;
	private QuestionAnswer mAnsewer;
	private User mUesr;
	private Button mGuanzhu;
	TextView text_patient_name;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_question_detail);

		init();
		isViewProfile = getIntent().getBooleanExtra(Constant.IDENTITY_KEY_1,
				false);

		list_question_detail = (PullToRefreshListView) findViewById(R.id.list_question_detail);
		list_question_detail.setOnRefreshListener(this);

		list_question_detail.setPullLoadEnabled(false);
		list_question_detail.setPullRefreshEnabled(false);
		list_question_detail.setScrollLoadEnabled(false);

		View headView = LayoutInflater.from(activity).inflate(
				R.layout.view_question_detail_head, null);
		headView.findViewById(R.id.person_detail_head).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (mUesr != null) {
							CommonUtility.toPersonHomeActivity(activity, mUesr);
						}
					}
				});
		mGuanzhu = (Button) headView.findViewById(R.id.guanzhu);
		mGuanzhu.setOnClickListener(this);
		mPersonDetail = (PersonDetailView) headView
				.findViewById(R.id.person_detail_head);
		footView = (LinearLayout) LayoutInflater.from(activity).inflate(
				R.layout.view_search_more_question_detail, null);
		// list_question_detail.getListView().addFooterView(footView);
		list_question_detail.getListView().addHeaderView(headView);

		img_loading = (ImageView) footView.findViewById(R.id.img_loading);
		btn_load_more_question_detail = (Button) footView
				.findViewById(R.id.btn_load_more_question_detail);
		ll_buliang_guominshi = (LinearLayout) headView
				.findViewById(R.id.ll_buliang_guominshi);
		OTab tab = findViewById(R.id.tab, OTab.class);
		tab.setVisibility(View.GONE);
		params.put(Constant.PARAM_API, "Question.GetList");
		params.put("pageSize", Constant.pageSize);
		params.put(Constant.PARAM_TOKEN, GlobalSettings.sToken);
		try {
			if (isViewProfile) {
				user = new JSONObject(getIntent().getStringExtra(
						Constant.IDENTITY_KEY));
				setNavTitle(user.getString("Name"));
			} else {
				setNavTitle("问题详情");
				question = new JSONObject(getIntent().getStringExtra(
						Constant.IDENTITY_KEY));
				mAnsewer = JsonUtil.convertFromObject(question,
						QuestionAnswer.class);
				user = question.getJSONObject("Patient_User");
				mUesr = JsonUtil.convertFromObject(user, User.class);
			}
			params.put("uid", user.getString("Uid"));
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (!CommonUtility.isNull(question)) {
			array.add(mAnsewer);
		} else {
			btn_load_more_question_detail.performClick();
		}
		adapter = new QuestionDetailAdapter();
		adapter.setActivity(this);
		adapter.setDataProvider(array);
		list_question_detail.setAdapter(adapter);
		list_question_detail.getListView().setDescendantFocusability(
				ViewGroup.FOCUS_BLOCK_DESCENDANTS);

		text_job = (TextView) headView.findViewById(R.id.text_job);
		text_guominshi = (TextView) headView.findViewById(R.id.text_guominshi);
		text_bingshi = (TextView) headView.findViewById(R.id.text_bingshi);

		img_patient_icon = (OImageView) headView
				.findViewById(R.id.img_patient_icon);

		text_patient_name = (TextView) headView
				.findViewById(R.id.text_patient_name);

		ll_yaowuguomin = (LinearLayout) headView
				.findViewById(R.id.ll_yaowuguomin);
		ll_bingshi = (LinearLayout) headView.findViewById(R.id.ll_bingshi);

		loadUserInfo();

		try {
			if (!CommonUtility.isNull(GlobalSettings.sUser)
					&& GlobalSettings.sUser.Uid != user.getInt("Uid")) {

				RequestTaskIntercept.requestIntercept(activity,
						Constant.URL.REQUEST, new RequestHandler(activity,
								new HandlerCallback() {

									@Override
									public void callback(Object o) {
										if (!CommonUtility.isNull(o)) {
											JSONObject object = (JSONObject) o;
											if (CommonUtility
													.response200(object)) {
												try {
													JSONArray array = object
															.getJSONArray(Constant.JSON_PARAM_RES);

													if (array.length() > 0) {
														mGuanzhu.setText("取消关注");
													} else {
														mGuanzhu.setText("关注");
													}
												} catch (Exception e) {
													e.printStackTrace();
												}
											}
										}
									}
								}), false, CommonUtility.params(new String[] {
								Constant.PARAM_API, "uids",
								Constant.PARAM_TOKEN }, new String[] {
								"Follow.Check", user.getString("Uid"),
								GlobalSettings.sToken }));

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		IntentFilter filter = new IntentFilter(Constant.RECIVER_COMMENT);
		registerReceiver(receiver, filter);
		getQuestionAnswer();
	}
	public void getQuestionAnswer(){
		QuestionGetTask task = new QuestionGetTask();
		QuestionGetRequest req = new QuestionGetRequest();
		req.qids = new ArrayList<Long>();
		req.qids.add(mAnsewer.Qid);
		req.token = GlobalSettings.sToken;
		req.appname = Constant.APP_NAME;
		task.setRequest(req);				
		task.addListener(new NetTaskListener<QuestionGetTask.QuestionGetRequest, QuestionGetTask.QuestionGetResponse>() {

			@Override
			public void onComplete(
					INetTask<QuestionGetRequest, QuestionGetResponse> task,
					QuestionGetResponse response) {
				if(response!=null&&response.Res.size()>0){
					array.clear();
					array.add(response.Res.get(0));
					adapter.notifyDataSetChanged();
				}
			}

			@Override
			public void onException(
					INetTask<QuestionGetRequest, QuestionGetResponse> task,
					Exception e) {
				e.printStackTrace();
			}
		});
		add(task);
	}
	public void loadData(boolean isShowDialog) {
		img_loading.setVisibility(View.VISIBLE);
		// ad = (AnimationDrawable) img_loading.getBackground();
		// ad.start();

		params.put("startQid", start_qid);

		try {
			QuestionGetListTask task = new QuestionGetListTask();
			QuestionGetListRequest req = new QuestionGetListRequest();
			req.startQid = start_qid;
			req.uid = user.getLong("Uid");
			task.setRequest(req);
			task.addListener(new NetTaskListener<QuestionGetListTask.QuestionGetListRequest, QuestionGetListTask.QuestionGetListResponse>() {

				@Override
				public void onException(
						INetTask<QuestionGetListRequest, QuestionGetListResponse> task,
						Exception e) {

				}

				@Override
				public void onComplete(
						INetTask<QuestionGetListRequest, QuestionGetListResponse> task,
						QuestionGetListResponse response) {
					list_question_detail.doComplete();
					// ad.stop();
					// ad = null;
					img_loading.setVisibility(View.GONE);
					if (!CommonUtility.isNull(response)) {
						try {
							if (response.ResultCode == 200) {

								array = response.Res.Questions;
								if (array.size() > 0) {

									if (array.size() < Constant.pageSize) {
										list_question_detail
												.setHasMoreData(false);
										btn_load_more_question_detail
												.setClickable(false);
										btn_load_more_question_detail
												.setText("没有更多问题了");
										btn_load_more_question_detail
												.setTextColor(0xff888888);
									} else {
										list_question_detail
												.setHasMoreData(true);
										btn_load_more_question_detail
												.setClickable(true);
										btn_load_more_question_detail
												.setTextColor(getResources()
														.getColor(
																R.color.border_blue));
									}
								} else {
									list_question_detail.setHasMoreData(false);
									btn_load_more_question_detail
											.setClickable(false);
									btn_load_more_question_detail
											.setText("没有更多问题了");
								}
								if (array.size() > 0) {
									start_qid = array.get(array.size() - 1).Qid;
								}
								if (CommonUtility.isNull(adapter)) {
									adapter = new QuestionDetailAdapter();
									adapter.setDataProvider(array);
									list_question_detail.setAdapter(adapter);
								} else {
									adapter.notifyDataSetChanged();
								}
							} else {
								CommonUtility.toast(activity,
										R.string.server_unavailable);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			});
			add(task);
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

	private User mUser;

	@Override
	protected void onResume() {
		super.onResume();
		loadData(false);
		// MobclickAgent.onResume(this);
	}

	void loadUserInfo() {
		try {
			
			mUser = JsonUtil.convertFromObject(user, User.class);
			if (mUser.Uid == GlobalSettings.sUid) {
				text_patient_name.setText(user.getString("Name"));
			}
			mPersonDetail.setMessage(mUser, mBitmapUtils,
					GlobalSettings.SERVER_IMG_URL + mUser.Pic
							+ GlobalSettings.IMG_SRC);

			if (CommonUtility.isNull(user.getString("Job"))) {
				text_job.setVisibility(View.GONE);
			} else {
				text_job.setText(user.getString("Job"));
			}

			String guominshi = CommonUtility.convertJSONArray2String(
					user.getJSONArray("DrugAllergen"), ",");
			if (CommonUtility.isNull(guominshi)) {
				ll_yaowuguomin.setVisibility(View.GONE);
			} else {
				text_guominshi.setText(guominshi);
			}

			String bingshi = CommonUtility.convertJSONArray2String(
					user.getJSONArray("MedicalHistory"), ",");
			if (CommonUtility.isNull(bingshi)) {
				ll_bingshi.setVisibility(View.GONE);
			} else {
				text_bingshi.setText(bingshi);
			}

			if (!ll_yaowuguomin.isShown() && !ll_bingshi.isShown()) {
				ll_buliang_guominshi.setVisibility(View.GONE);
			}
			if (CommonUtility.isDoctor()
					|| user.getInt("Uid") == GlobalSettings.sUser.Uid) {
				img_patient_icon.setVisibility(View.VISIBLE);

				/*
				 * mBitmapUtils.display(img_patient_icon,
				 * GlobalSettings.SERVER_IMG_URL + user.getString("Pic") +
				 * Constant.IMG_TH, new OBitmapLoadCallBack<View>());
				 */
				CommonUtility.displayHeadImage(img_patient_icon, mBitmapUtils,
						GlobalSettings.SERVER_IMG_URL + user.getString("Pic")
								+ Constant.IMG_TH, getResources(),
						user.getInt("Sex"));

				/*
				 * 
				 * text_patient_name.setVisibility(View.VISIBLE);
				 */
			}

		} catch (Exception e) {
		}
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		start_qid = null;
		array.clear();
		loadData(false);
	}

	@Override
	public void onPullUpToLoadMore(PullToRefreshBase<ListView> refreshView) {
		loadData(false);
	}

	public void onClick(View view) {
		super.onClick(view);
		int id = view.getId();
		if (id == R.id.guanzhu) {
			TextView tv = (TextView) view;
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put(Constant.PARAM_API, "Follow.Set");
			params.put(Constant.PARAM_TOKEN, GlobalSettings.sToken);
			final boolean isGuanzhu = tv.getText().toString().equals("取消关注");

			try {
				params.put("uids", user.getString("Uid"));
			} catch (Exception e) {
				e.printStackTrace();
			}
			FollowSetTask task = new FollowSetTask();
			FollowSetRequest req = new FollowSetRequest();
			if (!isGuanzhu) {
				req.method = "add";
			} else {
				req.method = "cancle";
			}
			req.token = GlobalSettings.sToken;
			try {
				ArrayList<Long> uids = new ArrayList<Long>();
				uids.add(user.getLong("Uid"));
				req.uids = uids;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			task.setRequest(req);
			task.addListener(new NetTaskListener<FollowSetTask.FollowSetRequest, FollowSetTask.FollowSetResponse>() {

				@Override
				public void onComplete(
						INetTask<FollowSetRequest, FollowSetResponse> task,
						FollowSetResponse response) {
					if (!CommonUtility.isNull(response)) {

						if (response.ResultCode == 200) {
							CommonUtility.toast(activity, "关注患者成功");
							if (!isGuanzhu) {
								mGuanzhu.setText("取消关注");
							} else {
								mGuanzhu.setText("关注");
							}
						} else {
							CommonUtility.toast(activity, "关注失败");
						}
					}
				}

				@Override
				public void onException(
						INetTask<FollowSetRequest, FollowSetResponse> task,
						Exception e) {

				}
			});
			add(task);
		} else if (id == R.id.btn_load_more_question_detail) {
			view.setClickable(false);
			btn_load_more_question_detail.setTextColor(0xff888888);
			loadData(false);
		}
	}

	AnimationDrawable ad;

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			try {
				QuestionAnswerExtra extra = new QuestionAnswerExtra();
				extra.getFrom(intent);
				QuestionAnswer answer = extra.getQuestionAnswer();

				QuestionAnswer o = null;
				int size = array.size();
				for (int i = 0; i < size; i++) {
					o = array.get(i);
					if (o.Qid == answer.Qid) {
						array.remove(i);
						array.add(answer);
						adapter.notifyDataSetChanged();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			QuestionDetailActivity.this.finish();
		}
	};

	protected void onNewIntent(Intent intent) {

	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		CommonUtility.unRegisteReciver(activity, receiver);
	}

	/*
	 * @Override public void onPause() { super.onPause();
	 * MobclickAgent.onPause(getContext()); }
	 */

}
